import { createRouter, createWebHistory } from 'vue-router'
import { useCounterStore } from "@/store/index";
import Login from '../views/Login.vue'
import Cart from '../views/Cart.vue'
import My from '../views/My.vue'
import Detail from '../views/Detail.vue'


const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/cart',
    component: Cart
  },
  {
    path: '/my',
    component: My
  },
  {
    path: '/detail',
    component: Detail
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
// 8、配置路由守卫在未登录情况下访问我的页面跳转登录页
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    next()
  } else {
    const store = useCounterStore();
    const token = store.userInfo.token
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
